// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
const axios = require('axios');
const {
  Context,
  Signer
} = require('jdcloud-sdk-signer')

cloud.init()
let db = cloud.database()
const _ = db.command

/**
 * 因为京东neuhub平台服务器崩溃，所以改用京东云垃圾分类API
 */

/**
 * 京东API配置
 * 垃圾分类api
 * 
 * 申请地址：https://www.jdcloud.com/cn/products/garbage-classification
 */
let jdaiyuncofig = {
  accessKeyId: '',
  secretAccessKey: ''
}

function getAuthorization() {
  let ctx = new Context('nativecontainer.internal.cn-north-1.jdcloud-api.com', '/jdai/*', 'POST', null, '', 'cn-north-1')
  ctx.buildNonce()
  let signer = new Signer(ctx, jdaiyuncofig)
  let auth = signer.sign(new Date())
  return auth
}

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let {
    APPID,
    OPENID
  } = wxContext
  const app = new TcbRouter({
    event
  })

  //提供通过文本进行垃圾分类查询的能力
  app.router('garbageTextSearch', async (ctx, next) => {
    let {
      text,
      devIntegral
    } = event

    let user = db.collection('user')
    let {
      total
    } = await user.where({
      OPENID: OPENID,
      integral: _.gte(devIntegral)
    }).count()
    if (!total) {
      ctx.body = {
        code: 0,
        msg: "积分不足"
      }
      return
    }

    await user.where({
      OPENID: OPENID,
      integral: _.gte(devIntegral)
    }).update({
      data: {
        integral: _.inc(-Number(devIntegral))
      }
    })

    let auth = getAuthorization()
    ctx.body = axios.post(`https://aiapi.jdcloud.com/jdai/garbageTextSearch`, {
      text: text,
      cityId: '310000'
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': auth
      }
    }).then(res => {
      return res.data
    })
  })

  //通过图片进行垃圾分类查询的能力
  app.router('garbageImageSearch', async (ctx, next) => {
    let {
      imgBase64,
      devIntegral
    } = event

    let user = db.collection('user')
    let {
      total
    } = await user.where({
      OPENID: OPENID,
      integral: _.gte(devIntegral)
    }).count()
    if (!total) {
      ctx.body = {
        code: 0,
        msg: "积分不足"
      }
      return
    }

    await user.where({
      OPENID: OPENID,
      integral: _.gte(devIntegral)
    }).update({
      data: {
        integral: _.inc(-Number(devIntegral))
      }
    })

    ctx.body = {
      code: 1
    }
    const img = await cloud.downloadFile({
      fileID: imgBase64
    })
    let buffer = new Buffer.from(img.fileContent)
    cloud.deleteFile({
      fileList: [imgBase64]
    })
    let str = buffer.toString('base64')

    let auth = getAuthorization()
    ctx.body = axios.post(`https://aiapi.jdcloud.com/jdai/garbageImageSearch`, {
      imgBase64: str,
      cityId: '310000'
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': auth
      }
    }).then(res => {
      return res.data
    })

  });

  //获取用户openID
  app.router('openId', async (ctx, next) => {
    ctx.body = {
      openId: OPENID
    }
  })
  return app.serve()
}